<?php
namespace App\Services;
use Xhat\Payjs\Payjs;
use Log;
use GuzzleHttp\Client;

class PaymentService
{
    /* *
     * JSAPI支付
     * */
    public static function getPayjs($title,$price,$out_trade_no,$uid,$openid,$mchid,$key)
    {
        // 配置通信参数
        $config = [
            'mchid' => $mchid,   // 配置商户号
            'key'   => $key,   // 配置通信密钥
        ];

        // 初始化
        $payjs = new Payjs($config);
        // 构造订单基础信息
        $data = [
            'body' => $title,                                           // 订单标题
            'total_fee' => $price*100,                                  // 订单金额
            'out_trade_no' => $out_trade_no,                            // 订单号
            'attach' => $uid,                                           // 订单附加信息(可选参数)
            'notify_url' => 'https://'.$_SERVER['SERVER_NAME'].'/api/wechat_notify',     // 异步通知地址(可选参数)
            'callback_url' => 'https://'.$_SERVER['SERVER_NAME'].'/goods_orders/'.$out_trade_no,     // 同步通知地址(可选参数)
            'openid' => $openid,                                        // OPENID (必选参数)
        ];
        // openid获取方式很简单,调用这个链接会自动返回
        // https://payjs.cn/api/openid?mchid=1605177750&callback_url=http://www.example.com/abc?uid=32

        $result = $payjs->jsapi($data);
        return $result;
    }


    public static function getPayjsCheck($payjs_order_id)
    {
        // 配置通信参数
        $config = [
            'mchid' => '1606624545',   // 配置商户号
            'key'   => 'GmfCGpBgwVAcTYvY',   // 配置通信密钥
        ];

        // 初始化
        $payjs = new Payjs($config);
        return $payjs->check($payjs_order_id);
    }

    // 退款
    public static function getPayjsrefund($payjs_order_id)
    {
        // 配置通信参数
        $config = [
            'mchid' => '1606624545',   // 配置商户号
            'key'   => 'GmfCGpBgwVAcTYvY',   // 配置通信密钥
        ];

        // 初始化
        $payjs = new Payjs($config);
        return $payjs->refund($payjs_order_id);
    }

    public static function wechatQrcodesPay($payment,$money,$out_trade_no,$subject,$attach)
    {
        $key = "NTZiOWY5MWRlOTVkYzFhNGJkZDdjMGA";
        $secret = "eyJpdiI6IncwYXhwS2tIb2FzaWt5RnpJUlgrSWc9PSIsInZhbHVlIjoidTlQNHdSdFdOWjlKU1p4ZXFka09jNWgzQjRZdHlRMzNqVnRnYnl6K2JMUDNOTDMrL1VjODkvVmxrWGtoL0RJOSIsIm1hYyI6ImM2NjllZGE4NWI1MTM0ZTcwYzljZTQxYjIxM2FiNzYwYjE5OTRhMGEwN2Y4OTA0M2NhZjQxMTAyOTc0YjUzZjQifQ==";

        $client = new Client();
        $host = "http://pay.n6nck.cn/api/version/1/pay/generate_order?key=".$key."&secret=".$secret."&payment=".$payment."&money=".$money."&out_trade_no=".$out_trade_no."&subject=".$subject."&attach=".$attach;
        $response = $client->request('GET', $host);
        $appleBody = json_decode($response->getBody());
        return $appleBody;

        // $client = new Client();
        // $nresponse = $client->request('POST', $users_config->notify_url, ['form_params' => [
        //     'trade_no' => $order->orders_id,
        //     'money' => $order->money,
        //     'out_trade_no' => $order->out_trade_no,
        //     'attach' => $order->attach,
        //     'time' => $time,
        //     'token' => $token,
        //     'payment' => $order->payment,
        // ]]);
    }


    public static function FuyilaiPay($money,$out_trade_no,$attach)
    { 
        $appid="0000000613";                            //付易来APPID
        $appkey="slgi7bediwjpkztf0xest6vzvec9yhb6";     //付易来APPKEY

        $form_params = [
            'appid' => $appid,
            'body' => $attach,                          //扩展数据,原路返回
            'gooddes' => "订单问题联系客服微:wx1877955561",//商品描述
            'goodname' => "订单问题联系客服微:wx1877955561",//商品名称
            'ip' => $_SERVER["REMOTE_ADDR"],//IP
            'notify_url' => "http://**/api/version/1.1/fuyilai_notify_url",//异步通知地址
            'out_trade_no' => $out_trade_no,//订单号
            'return_url' => "http://**/fuyilai_back",//同步通知
            'total_fee' => $money*100,//金额,单位分
        ];

        $str = "appid={$form_params['appid']}&body={$form_params['body']}&gooddes={$form_params['gooddes']}&goodname={$form_params['goodname']}&ip={$form_params['ip']}&notify_url={$form_params['notify_url']}&out_trade_no={$form_params['out_trade_no']}&return_url={$form_params['return_url']}&total_fee={$form_params['total_fee']}&key={$appkey}";
        $sign = strtoupper(md5((string)$str));
        $form_params['sign'] = $sign;

        $client = new Client;
        $response = $client->request("POST",  "http://api.fuyilai.com/version1.0/wx", [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => $form_params
        ]);
        $body = $response->getBody();
        return json_decode($body,true);
    }

    public static function heemoneyPay($money,$out_trade_no,$attach)
    { 
        $url = "https://pay.heemoney.com/v1/ApplyPay"; //请求地址
        //公共参数
        $method = "heemoney.pay.applypay"; //具体业务接口名称
        $version = "1.0"; //版本号

        $app_id = "hyp21032911393100003645888B5BAF4"; //应用ID，
        $mch_uid = "1139312129164"; //  商户统一编号//
        $key = "A5D7A0347DDA40CA967911B6"; //密钥

        $charset = "UTF-8"; //编码格式
        $timestamp = date('YmdHis'); //发送请求的时间
        $biz_content = ""; //请求参数集合，Json格式，长度不限，具体参数见如下业务参数
        $sign_type = "MD5"; //商户生成签名字符串所使用的签名算法类型
        $sign = ""; //商户请求参数的签名串

        //业务参数
        $subject = "订单问题联系客服微:wx1877955561"; //订单标题
        $total_fee = $money*100; //订单总金额，单位为分
        $channel_type = "WX_JSAPI"; //通道类型
        $client_ip = "127.0.0.1"; //用户端ip
        $attach = '{"openid":"'.$attach.'"}'; //附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用格式：{“key1”:”value1”,”key2”:”value2”,…}
        $pay_option = ""; //支付参数信息
        $meta_option = ""; //商户定制信息，格式：{“key1”:”value1”,”key2”:”value2”,…}
        $notify_url = "http://**/api/version/1.1/heemoney_notify_url"; //异步通知的地址
        $return_url = "http://**/pay/heemoney_back"; //同步通知地址

        $biz_content = array("out_trade_no" => $out_trade_no, "subject" => $subject, "total_fee" => $total_fee, "client_ip" => $client_ip, "notify_url" => $notify_url, "return_url" => $return_url, "channel_type" => $channel_type, "attach" => $attach);
        $biz_content = json_encode($biz_content);
        $biz_content = str_replace("\\/", "/", $biz_content);
        $sign_str = 'app_id=' . $app_id . '&biz_content=' . $biz_content . '&charset=' . $charset . '&mch_uid=' . $mch_uid . '&method=' . $method . '&sign_type=' . $sign_type . '&timestamp=' . $timestamp . '&version=' . $version . '&key=' . $key;
        $signString = strtoupper(md5($sign_str));

        $form_params = array('method' => $method, 'version' => $version, 'app_id' => $app_id, 'mch_uid' => $mch_uid, 'charset' => $charset, 'sign_type' => $sign_type, 'timestamp' => $timestamp);
        $form_params['biz_content'] = $biz_content;
        $form_params['sign'] = $signString;

        $client = new Client;
        $response = $client->request("POST",  "https://pay.heemoney.com/v1/ApplyPay", [
            'headers' => [
                'Content-Type' => 'application/json; charset=utf-8',
            ],
            'json' => $form_params
        ]);
        $body = $response->getBody();
        return json_decode($body,true);
    }


    public static function adapayPay($price,$out_trade_no,$open_id)
    { 
        # 支付设置
        $payment_params = [
            'app_id'=> 'app_86629dda-1422-4a30-8c10-90371869d21c',
            'order_no'=> $out_trade_no,
            'pay_channel'=> 'wx_pub',
            'time_expire'=> date("YmdHis", time()+86400),
            'pay_amt'=> $price,
            'goods_title'=> '订单问题联系客服微:wx1877955561',
            'goods_desc'=> '订单问题联系客服微:wx1877955561',
            'description'=> '订单问题联系客服微:wx1877955561',
            'device_id'=> ['device_id'=>"1111"],
            'notify_url' => "http://**/api/version/1.1/adapay_notify_url",
            'expend'=> [
                'open_id'=> $open_id
            ]
        ];

        $url = "https://api.adapay.tech/v1/payments";
        $api_key = "api_live_ba62042e-a26d-4d56-adbf-2dd371c2a79a";
        $rsa_private_key = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMQkLBbDSAUD/iV5gCzkdyYCbqridRUhKh0D3LOX07RpejPeFnKZCSBT7KVY44nFSLB/ldXvIf7gu3ApVgCMczi5Bz0JGAwIypmaYQdxd1Ps/hIaBdAUZvX+ieSQoLU21CkB2IDp/kP8vSm5DqCahfxIh7SY1EHuFbNj3Ieez1gbAgMBAAECgYBsZoFnYy3ed8Jx+6B3Lx0aiKWZE+cZcmbP+l5zcymxv8ml+Mv3MdT1ZOyYxXObpMjzos+wmKT1NEbjSjUZwIW8j3W49XYE6EoxP/LqdlYBkxHDVbp60ul49IUH31fwxPKFLDNiFA1mpzLxTrjhCG/sX4iU2W6LKDQ2ss2BAN58wQJBAO7OmMgN2HNAJxyPzBclULRZ4YEGe4V8J3bu8ZQ8gg14mCsddejgY2H0yn4EwdLzt3XM+5ByGW9VphD0QiseeWMCQQDSQzZW7enAH9LpOGDNzozImvwLULE5FRLnoU65jvleM9Q/XDQkxV4u4wAVrRzTm7vvgNHXTt9r9DiWIsuHFr/pAkAtocap+5NPuoN+vq+GALhiLgacLAvwXt//pvr8k29aeZ/CJVgBjtcOwcLrv6b102JMHUY4vMTFdH1OIg5+xMz3AkAwsuaEDciE+hn0cF1jbYKH9/WGfWL+sJXXVjIQoj+5hNGU9zsQhTICNAtR+e1iSYCmwTRY5Oi0bTUp+Ncg67D5AkAVWCn4B9oNyIjWq9LVuAt+fwoO4I4C0Lj7LE0PHeNLDXiGN7PPNBOUe0/MZ2uWKjr/sL6VW7otVZxH+316GEgS";

        $params = $payment_params;
        $params['currency'] = 'cny';
        $params['sign_type'] = 'RSA2';
        if (is_array($params)){
            $Parameters = array();
            foreach ($params as $k => $v)
            {
                $Parameters[$k] = $v;
            }
            $data = $url . json_encode($Parameters);
        }else{
            $data = $url . $params;
        }

        $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsa_private_key, 64, "\n", true)."\n-----END PRIVATE KEY-----";

        openssl_sign($data, $signature, $key);
        $signature = base64_encode($signature);

        $client = new Client;
        $response = $client->request("POST",  "https://api.adapay.tech/v1/payments", [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => $api_key,
                'Signature' => $signature,
                'sdk_version' => 'v1.3.1',
            ],
            'json' => $params
        ]);
        $body = $response->getBody();
        $bodydata = json_decode($body,true);
        return json_decode($bodydata["data"],true);
    }


}
